package cn.hl.hm.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.vizhuo.client.base.AbstractVo;
import com.vizhuo.client.business.appmanage.constant.AppPushConstant;
import com.vizhuo.client.business.appmanage.vo.AndroidPushCustomMessage;
import com.vizhuo.client.business.appmanage.vo.IOSPushCustomMessage;
import com.vizhuo.client.business.match.goods.vo.BoundsVo;
import com.vizhuo.push.umeng.base.PushClient;
import com.vizhuo.push.umeng.base.PushConstant;
import com.vizhuo.utils.DataUtil;
import com.vizhuo.utils.StringUtil;
import com.vizhuo.utils.match.MatchUtil;

import cn.hl.hm.entity.HelpInfo;
import cn.hl.hm.entity.Push;
import cn.hl.hm.service.AppPushToConsignerService;
import cn.hl.hm.service.AppPushToDriverService;
import cn.hl.hm.service.AppPushToLogisticsService;
import cn.hl.hm.service.PushToAppIService;

/**
 * 推送服务封装类 (推送业务可以直接调用此类，最好不要自行直接注入友盟实现类)
 * @author dcq 作者 E-mail: ding_chuanqin@163.com
 * @date 创建时间：2016年7月1日 下午3:10:39
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
@Service("pushToAppServiceImpl")
public class PushToAppServiceImpl extends UmengAppPushServiceImpl implements PushToAppIService {

    private static Logger log = LoggerFactory.getLogger(PushToAppServiceImpl.class);
    
    /**
     * 注入的友盟推送（物流公司）
     */
    @Autowired
    @Qualifier("appPushToLogisticsService_umeng")
    private AppPushToLogisticsService appPushToLogisticsServiceImpl;

    /**
     * 注入的友盟推送（司机）
     */
    @Autowired
    @Qualifier("appPushToDriverService_umeng")
    private AppPushToDriverService appPushToDriverServiceImpl;

    /**
     * 注入的友盟推送（商户）
     */
    @Autowired
    @Qualifier("appPushToConsignerService_umeng")
    private AppPushToConsignerService appPushToConsignerServiceImpl;
    
    
    @Autowired
    @Qualifier("consignerPushAndroidClient")
    private PushClient consignerPushAndroidClient;

    @Autowired
    @Qualifier("consignerPushIOSClient")
    private PushClient consignerPushIOSClient;

    @Autowired
    @Qualifier("logisticsinfoPushAndroidClient")
    private PushClient logisticsinfoPushAndroidClient;

    @Autowired
    @Qualifier("driverPushAndroidClient")
    private PushClient driverPushAndroidClient;

    @Autowired
    @Qualifier("driverPushIOSClient")
    private PushClient driverPushIOSClient;

    @Autowired
    @Qualifier("logisticsinfoPushIOSClient")
    private PushClient logisticsinfoPushIOSClient;
    

    /**
     * 推送消息-单播
     */
    @Override
    public void pushMsgByAccount(String phoneNumber, String accountType, String title, String pushText) {
        log.info("enter pushMsgByAccount of PushToAppServiceImpl ");
        try {

            if (DataUtil.isEnterprise(accountType)) {
                // 调用友盟推送业务的接口（货主、信息部）
                appPushToLogisticsServiceImpl.pushSysMsgByAccount(AppPushConstant.OPERATION_TYPE_SYS_MSG, phoneNumber,
                        title, pushText);
            } else if (DataUtil.isDriver(accountType)) {
                // 调用友盟推送业务的接口（司机）
                appPushToDriverServiceImpl.pushSysMsgByAccount(AppPushConstant.OPERATION_TYPE_SYS_MSG, phoneNumber,
                        title, pushText);
            }

        } catch (Exception e) {
            log.info("推送消息发生异常：" + e.getMessage());
        }
    }

    // 活动推送接口
    @Override
    public void pushActivitByAccount(String accountType, String title, String pushText) {
        log.info("enter pushActivitByAccount of PushToAppServiceImpl ");
        try {
            if (DataUtil.isEnterprise(accountType)) {
                // 调用友盟推送业务的接口（物流公司）
                appPushToLogisticsServiceImpl.pushSysMsgAll(AppPushConstant.OPERATION_ACTIVIT_EXPRESS, title, pushText);
            } else if (DataUtil.isDriver(accountType)) {
                // 调用友盟推送业务的接口（司机）
                appPushToDriverServiceImpl.pushSysMsgAll(AppPushConstant.OPERATION_ACTIVIT_EXPRESS, title, pushText);
            } else if (DataUtil.isConsigner(accountType)) {
                // 调用友盟推送业务的接口（发货人）
                appPushToConsignerServiceImpl.pushSysMsgAll(AppPushConstant.OPERATION_ACTIVIT_EXPRESS, title, pushText);
            }

        } catch (Exception e) {
            log.info("推送消息发生异常：" + e.getMessage());
        }
    }

    // 设置黑名单推送
    @Override
    public void pushBlackByAccount(String phoneNumber) {
        log.info("enter pushBlackByAccount of PushToAppServiceImpl ");
        try {
            if (StringUtil.isBlank(phoneNumber)) {
                return;
            }
            String pushText = phoneNumber + AppPushConstant.PUSH_BLACKED_CONTENT;
            // 调用友盟推送业务的接口（货主、信息部）
            appPushToLogisticsServiceImpl.pushSysMsgAll(AppPushConstant.OPERATION_BLACK_EXPRESS,
                    AppPushConstant.PUSH_BLACKED_TITLE, pushText);
            // 调用友盟推送业务的接口（司机）
            appPushToDriverServiceImpl.pushSysMsgAll(AppPushConstant.OPERATION_BLACK_EXPRESS,
                    AppPushConstant.PUSH_BLACKED_TITLE, pushText);

        } catch (Exception e) {
            log.info("推送消息发生异常：" + e.getMessage());
        }
    }


    /**
     * 审核信息推送
     */
    @Override
    public void pushMsgByAccount(String phoneNumber, String accountType, String title, String pushText,
            AbstractVo abstractVo) {
        log.info("enter pushMsgByAccount of PushToAppServiceImpl " + "审核的accountType为" + accountType);
        try {

            if (DataUtil.isEnterprise(accountType)) {
                // 调用友盟推送业务的接口（物流公司）
                appPushToLogisticsServiceImpl.pushMsgByAccount(phoneNumber, title, pushText, accountType, abstractVo);
            } else if (DataUtil.isDriver(accountType)) {
                // 调用友盟推送业务的接口（司机）
                appPushToDriverServiceImpl.pushMsgByAccount(phoneNumber, title, pushText, accountType, abstractVo);
            } else if (DataUtil.isConsigner(accountType)) {
                // 调用友盟推送业务的接口（商户）
                appPushToConsignerServiceImpl.pushMsgByAccount(phoneNumber, title, pushText, accountType, abstractVo);
            }

        } catch (Exception e) {
            log.info("推送消息发生异常：" + e.getMessage());
        }
    }

    // 系统消息-所有设备
    @Override
    public void pushSysMsgAll(String title, String pushText) {
        try {
            appPushToLogisticsServiceImpl.pushSysMsgAll(title, pushText);
            appPushToDriverServiceImpl.pushSysMsgAll(title, pushText);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 推送-帮扶
    @Override
    public void pushHelp(HelpInfo helpInfo) {
        log.info("enter pushHelp of PushToAppServiceImpl ");
        if (MatchUtil.isNullLnglat(helpInfo.getLng()) || MatchUtil.isNullLnglat(helpInfo.getLat())) {
            return;
        }

        BoundsVo reqbBoundsVo = new BoundsVo();
        reqbBoundsVo.setLng(helpInfo.getLng());
        reqbBoundsVo.setLat(helpInfo.getLat());
        BoundsVo respBoundsVo = appPushToDriverServiceImpl.getsubLnglat(reqbBoundsVo, 50);
        if (respBoundsVo == null || MatchUtil.isNullLnglat(respBoundsVo.getSubLngfrom())
                || MatchUtil.isNullLnglat(respBoundsVo.getSubLatfrom())) {
            return;
        }
        // 给符合周边的司机推送
        try {
            appPushToDriverServiceImpl.pushHelp(helpInfo, respBoundsVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 推送测试-所有设备(列播方式)
    @Override
    public void pushTestAll(Push push) {
        try {
            if (push.getPushCount() > 50) {
                push.setPushCount(50);
            }
            for (int i = 0; i < push.getPushCount(); i++) {
                // 调用友盟推送业务的接口（货主、信息部）
                appPushToLogisticsServiceImpl.pushTest(AppPushConstant.OPERATION_TYPE_SYS_MSG_ALL, push.getTitle() + i,
                        push.getContext() + i);
                // 调用友盟推送业务的接口（司机）
                appPushToDriverServiceImpl.pushTest(AppPushConstant.OPERATION_TYPE_SYS_MSG_ALL, push.getTitle() + i,
                        push.getContext() + i);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    // 公共推送
    @Override
    public void pushCommon(Push push) {
    		//System.out.println(push.getTokenStr().length);
            try {
            	if (push.getTokenStr() != null && push.getTokenStr().length > 0) {
                    StringBuffer sbAndroid = new StringBuffer();
                    StringBuffer sbIos = new StringBuffer();
                    //循环分出 IOS , Android token数组
                    for(int i = 0; i < push.getTokenStr().length; i++){
                    	//System.out.println(push.getTokenStr()[i].length());
                    	if(push.getTokenStr()[i].length() == 44){
                    		sbAndroid.append(push.getTokenStr()[i]);
                    		sbIos.append(push.getTokenStr()[i]);

                    	}else{
                    		sbIos.append(push.getTokenStr()[i]);
                    		sbAndroid.append(push.getTokenStr()[i]);
                    	}
                    }
            		
                    //AndroidPush组装
	                AndroidPushCustomMessage custom = new AndroidPushCustomMessage();
	                custom.setType(push.getOperationType());
	                custom.setContext(push.getContext());
	                custom.setPushtype(push.getPtype());
	                custom.setPushoid(push.getPushoid());
	                custom.setActivityUrl(push.getActivityUrl());
	                custom.setTimeNode(push.getTimeNode());
	                custom.setOrderStatus(push.getOrderStatus());
	                custom.setBizzType(push.getBizzType());

	                	if(push.getPushClient().equals("consignerPushClient")){
	                		push2Android(push.getOperationType(), PushConstant.DISPLAY_TYPE_MESSAGE, PushConstant.TYPE_LISTCAST, push.getTitle(), push.getContext(), String.valueOf(sbAndroid), consignerPushAndroidClient, custom);
	                	}else if(push.getPushClient().equals("driverPushClient")){
	                		push2Android(push.getOperationType(), PushConstant.DISPLAY_TYPE_MESSAGE, PushConstant.TYPE_LISTCAST, push.getTitle(), push.getContext(), String.valueOf(sbAndroid), driverPushAndroidClient, custom);
	                	}
//                    System.out.println("test android push执行后");
	                //IOSPush组装
	                IOSPushCustomMessage customIOS = new IOSPushCustomMessage();
	                customIOS.setType(push.getOperationType());
	                customIOS.setContext(push.getContext());
	                customIOS.setPushtype(push.getPtype());
	                customIOS.setPushoid(push.getPushoid());
	                customIOS.setActivityUrl(push.getActivityUrl());
	                customIOS.setTimeNode(push.getTimeNode());
	                customIOS.setOrderStatus(push.getOrderStatus());
                    customIOS.setBizzType(push.getBizzType());
	                	if(push.getPushClient().equals("consignerPushClient")){
	                		push2IOS(push.getOperationType(), PushConstant.TYPE_LISTCAST, push.getContext(), String.valueOf(sbIos) , consignerPushIOSClient, customIOS);
	                	}else if(push.getPushClient().equals("driverPushClient")){
	                		push2IOS(push.getOperationType(), PushConstant.TYPE_LISTCAST, push.getContext(), String.valueOf(sbIos) , driverPushIOSClient, customIOS);
	                	}
//                    System.out.println("test ios push执行后");
            	}
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

    // 反馈推送
    @Override
    public void pushFeedbackByAccount(String phoneNumber, String accountType, String pushText) {
        log.info("enter pushFeedbackByAccount of PushToAppServiceImpl ");
        try {
            if (DataUtil.isEnterprise(accountType)) {
                // 调用友盟推送业务的接口（物流公司）
                appPushToLogisticsServiceImpl.pushSysMsgByAccount(AppPushConstant.OPERATION_FEEDBACK_EXPRESS,
                        phoneNumber, AppPushConstant.PUSH_FEEDBACK_TITLE, pushText);
            } else if (DataUtil.isDriver(accountType)) {
                // 调用友盟推送业务的接口（司机）
                appPushToDriverServiceImpl.pushSysMsgByAccount(AppPushConstant.OPERATION_FEEDBACK_EXPRESS, phoneNumber,
                        AppPushConstant.PUSH_FEEDBACK_TITLE, pushText);
            } else if (DataUtil.isConsigner(accountType)) {
                // 调用友盟推送业务的接口（货主）
                appPushToConsignerServiceImpl.pushSysMsgByAccount(AppPushConstant.OPERATION_FEEDBACK_EXPRESS,
                        phoneNumber, AppPushConstant.PUSH_FEEDBACK_TITLE, pushText);
            }

        } catch (Exception e) {
            log.info("推送消息发生异常：" + e.getMessage());
        }

    }

    /**
     * 物流公司确认收货后给发货商推送消息的接口
     */
    @Override
    public void pushMsgByCofirmGetGoods(String phoneNumber, String accountType, String title, String pushText) {
        log.info("enter pushMsgByCofirmGetGoods of PushToAppServiceImpl ");
        try {

            if (DataUtil.isEnterprise(accountType)) {
                // 调用友盟推送业务的接口（物流公司）
                appPushToLogisticsServiceImpl.pushSysMsgByAccount(AppPushConstant.OPERATION_TYPE_TO_CONFIRM_GET_GOODS,
                        phoneNumber, title, pushText);
            } else if (DataUtil.isDriver(accountType)) {
                // 调用友盟推送业务的接口（司机）
                appPushToDriverServiceImpl.pushSysMsgByAccount(AppPushConstant.OPERATION_TYPE_TO_CONFIRM_GET_GOODS,
                        phoneNumber, title, pushText);
            } else if (DataUtil.isConsigner(accountType)) {
                // 调用友盟推送业务的接口（发货端）
                appPushToConsignerServiceImpl.pushSysMsgByAccount(AppPushConstant.OPERATION_TYPE_TO_CONFIRM_GET_GOODS,
                        phoneNumber, title, pushText);
            }

        } catch (Exception e) {
            log.info("推送消息发生异常：" + e.getMessage());
        }
    }

    /**
     * 单播测试
     */
    @Override
    public void pushTestUniCast(Push push) {
        String accountType = "2";
        try {
            if (push.getPushCount() > 50) {
                push.setPushCount(50);
            }
            for (int i = 0; i < push.getPushCount(); i++) {
                // 每隔5秒推送一次
                Thread.sleep(2000);
                // 调用友盟推送业务的接口（货主、信息部）
                appPushToLogisticsServiceImpl.pushMsgByAccount(push.getPhoneNumber(), push.getTitle() + i,
                        push.getContext() + i, accountType, null);
                // 调用友盟推送业务的接口（司机）
                // appPushToDriverServiceImpl.pushTest(AppPushConstant.OPERATION_TYPE_SYS_MSG_ALL,
                // push.getTitle() + i,
                // push.getContext() + i);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
